<template>
  <el-drawer :model-value="visible" :title="`关联房间门锁`" :size="mobile ? '100%' : '30%'" lock-scroll class="body-pd-clear" @close="handleClose">
    <div>
      <div v-loading="loading" class="mt20">
        <template v-if="list.length > 0">
          <div class="primary-section pv-12 ph-16" v-for="item in list" :key="item.id">
            <el-row align="middle">
              <el-col :span="16">
                <el-tag type="primary" effect="dark">{{ item.lockName }}</el-tag>
              </el-col>
              <el-col :span="8" align="right">
                <el-button link type="primary" @click="() => bindDevice(item.lockId)">绑定</el-button>
              </el-col>
            </el-row>
          </div>
        </template>
        <el-empty v-else description="无可关联的设备" />
      </div>
    </div>
  </el-drawer>
</template>
<script setup name="UnbindLockList">
import useAppStore from '@/store/modules/app'
import LockApi from "@/api/device/lock.js";
const { proxy } = getCurrentInstance()


const emit = defineEmits()
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  roomId: {
    type: [Number, String],
    default: ''
  },
})

const list = ref([])
const loading = ref(false)

const mobile = computed(() => useAppStore().device === 'mobile')

function handleClose() {
  emit('cancel')
}

function bindComplete() {
  emit('bind-complete')
}

function bindDevice(lockId) {
  if (!props.roomId || props.roomId === '') {
    proxy.$modal.msgWarning('请重新选择房间')
    return
  }
  LockApi.bindRoom({
    lockId,
    roomId: props.roomId
  }).then(res => {
    proxy.$modal.msgSuccess('操作成功')
    bindComplete()
  })
}

/* 获取列表 */
function getList() {
  loading.value = true
  list.value = []
  LockApi.getUnbindList().then(res => {
    list.value = res.data.map(it => {
      try {
        it.lockInfoObj = JSON.parse(it.lockInfo)
      } catch (e) {
        it.lockInfoObj = {}
      }
      return it
    })
    loading.value = false
  })
}

getList()
</script>

